package server;


import game.Player;
import game.PlayerController;

import java.net.ServerSocket;
import java.net.Socket;

import paintball.PaintballGame;

public class Server implements Runnable {
	private PaintballGame game;
	private Thread t;
	
	public Server(PaintballGame game) {
		this.game = game;
		this.t = new Thread(this);
		this.t.start();
	}

	@Override
	public void run() {
		int nreq = 1;
		try {
			ServerSocket sock = new ServerSocket(1234);
			for (;;) {
				Socket newsock = sock.accept();
				
				String playername = "Player " + nreq;
				System.out.println("Accepting new player: " + playername);
				
				int x = (int)(Math.random()*PaintballGame.screenWidth);
				int y = (int)(Math.random()*PaintballGame.screenHeight);
				
				Player p = PlayerController.addPlayer(playername, x, y, newsock);
				this.game.addConnection(new Connection(p, this.game));
				
				nreq++;
			}
		} catch (Exception e) {
			System.out.println("IO error " + e);
		}
		System.out.println("End!");
	}
}